package com.jackingod.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class URLGetter {
	private static final Logger logger = LogManager.getLogger("URLGetter");
	
	private static final int BUFFER_SIZE = 2048;
	private static long defaultFileNo = 1;
	private static final String defaultPostName = "txt";

	/***
	 * download the special url file, saved with the specail file name.
	 * @param url file'url
	 * @param file saved file
	 * @param override the file's override flag
	 */
	public static void download(URL url, File file, boolean override) {
		if (file == null) {
			file = getFile(url); 
		}
		
		File parent = file.getParentFile();
		if (parent != null && !parent.exists()) {
			parent.mkdirs();
		}
		
		if (file.exists()) {
			logger.info("file[" + file + "] has existed.");
			if (!override) {
				return;
			} else {
				logger.info("overwrite the file[" + file + "]");
			}
		}
		
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(url.openStream());
			bos = new BufferedOutputStream(new FileOutputStream(file));
			
			byte[] buffer = new byte[BUFFER_SIZE];
			int len = -1;
			while ((len = bis.read(buffer)) != -1) {
				bos.write(buffer, 0, len);
			}
			logger.info("finished download url[" + url + "], file=" + file);
		} catch (IOException e) {
			logger.error(e);
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					logger.error(e);
				}
			}
			
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					logger.error(e);
				}
			}
		}
	}
	
	/***
	 * download the special url file, saved with the special path
	 * @param url
	 * @param file
	 */
	public static void download(URL url, File file) {
		download(url, file, false);
	}
	
	/***
	 * download the special url file,default file name is "the number.txt"
	 * @param url
	 */
	public static void download (URL url) {
		download(url, getFile(url), false);
	}
	
	public static synchronized File getFile(URL url) {
		String path = url.getPath();
		logger.debug("path=" + path + " isNull=" + (path == null));
		if (path == null) {
			path = defaultFileNo + "." + defaultPostName;
		} else if ("".equals(path) || "/".endsWith(path)) {
			path += defaultFileNo + "." + defaultPostName;
		}
		return new File(path);
	}
	
	/*public static void main(String[] args) {
		try {
			URL url = new URL("http://www.baidu.com/");
			URLGetter.download(url);
		} catch (MalformedURLException e) {
			logger.error(e);
			return;
		}
	}*/
}
